package com.probiz.estoresf.customer.web.action;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.common.model.product.ProductReview;
import com.probiz.estore.common.model.product.ProductReviewAndVoteVO;
import com.probiz.estore.common.model.system.AppUser;
import com.probiz.estore.core.controller.GenericStoreFrontController;
import com.probiz.estore.core.event.EventUtil;
import com.probiz.estore.core.event.StoreFrontCache4ProductClearEvent;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.customer.service.ReviewEligibilityManager;
import com.probiz.estore.product.model.ProductReviewSearchCriteria;
import com.probiz.estore.product.service.ProdMainManager;
import com.probiz.estore.product.service.ProductManager;
import com.probiz.estore.product.service.ProductReviewManager;
import com.probiz.estore.product.service.ReviewVoteManager;
import com.probiz.estore.util.ipwry.IPSeeker;
import com.probiz.estore.webapp.util.RequestContext;
import com.probiz.estore.webapp.util.RequestUtil;

public class ProductReviewFrontController extends		GenericStoreFrontController<Product> {
	private ProductManager	productManager;
	private ProdMainManager	prodMainManager;
	private ProductReviewManager productReviewManager;
	private ReviewVoteManager reviewVoteManager;
	private ReviewEligibilityManager reviewEligibilityManager;
	protected void initController() throws Exception {
		mgr = productManager;
	}
	public void setProductManager(ProductManager productManager) {
		this.productManager = productManager;
	}
	
	public void setProdMainManager(ProdMainManager prodMainManager) {
		this.prodMainManager = prodMainManager;
	}	
	public void setProductReviewManager(ProductReviewManager productReviewManager) {
		this.productReviewManager = productReviewManager;
	}
	public void setReviewVoteManager(ReviewVoteManager reviewVoteManager) {
		this.reviewVoteManager = reviewVoteManager;
	}
	public void setReviewEligibilityManager(
			ReviewEligibilityManager reviewEligibilityManager) {
		this.reviewEligibilityManager = reviewEligibilityManager;
	}
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		// -----start:获得产品------
		Integer productId = productManager.getProductIdByUri(request.getRequestURI());
		Product product = productManager.getById(productId);
		// 没有找到相应产品或草稿状态的不能访问,直接进入找不到或已删除页面
		if (product == null	|| product.getStatus().shortValue() != Product.STATUS_ACTIVE.shortValue()) {
			try {
				response.sendError(404);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		// -----end:获得产品------

		// -----start:获得商品评论------
		SearchCriteria searchCriteria = this.createSearchCriteria(request);
		ProductReviewSearchCriteria productReviewSearchCriteria = new ProductReviewSearchCriteria();
		bindOnly(request, productReviewSearchCriteria,"productReviewSearchCriteria");
		productReviewSearchCriteria.setProductId(productId);
		productReviewSearchCriteria.setStatus(ProductReview.STATUS_SHOW);
		if(productReviewSearchCriteria.getOrderby() == null){
			productReviewSearchCriteria.setOrderby((short)0);
		}	
		List<ProductReview>  productReviewList = productReviewManager.searchByCriteriaForController(productReviewSearchCriteria, searchCriteria);
		// -----end:  获得商品评论------
		
		
	
		ModelAndView mv = new ModelAndView("customer/productReviewList");
		mv.addObject("product",product);
		mv.addObject("productReviewList",productReviewList);
		mv.addObject("productReviewSearchCriteria",productReviewSearchCriteria);
		
		// -----start:获得好中差评及五星次数------
		mv.addObject("scoreSpanCounts",productReviewManager.getCountsByScoreSpanAndProductId(product.getProductId()));
		mv.addObject("scoreLevelCounts",productReviewManager.getCountsByScoreLevelAndProductId(product.getProductId()));
		// -----end:  获得好中差评及五星次数------
		
		mv.addObject("currUser",(AppUser) RequestContext.getCurrentUser());
		return mv;
	}
	/**
	 * 对评论进行投票
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView reviewVote(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> data = new HashMap<String, Object>();
		ProductReviewAndVoteVO productReviewAndVoteVO = reviewVoteManager.doVote(request, RequestUtil.getInteger(request, "productReviewId"), RequestUtil.getInteger(request, "chosen").shortValue());
		data.put("result", productReviewAndVoteVO.getResult());
		data.put("productReviewId", productReviewAndVoteVO.getProductReview().getProductReviewId());
		data.put("usefulCount", productReviewAndVoteVO.getProductReview().getUsefulCount());
		data.put("unusefulCount", productReviewAndVoteVO.getProductReview().getUnusefulCount());
		
		ProductReview review = productReviewManager.getById(RequestUtil.getInteger(request, "productReviewId"));
		//清空该商品页面缓存
		EventUtil.getInstance().fire(new StoreFrontCache4ProductClearEvent(this,review.getProductId()));
		
		return this.getModelAndAjaxJsonView(data);
	}
	/**
	 * 渲染回复form
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView showReplyForm(HttpServletRequest request,HttpServletResponse response){
		ModelAndView mv = new ModelAndView("customer/include/productReviewReply");
		ProductReview productReview = productReviewManager.getById(RequestUtil.getInteger(request, "productReviewId"));
		mv.addObject("productReview", productReview);
		mv.addObject("currUser",(AppUser) RequestContext.getCurrentUser());
		return mv;
		
	}
	/**
	 * 发表回复
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView replyReview(HttpServletRequest request,HttpServletResponse response){
		//如果没登录，跳转到登录页
		if (ConfigUtil.getInstance().getCustomerReviewReplyRight().intValue() != ProductReview.REPLY_RIGHT_ANONYMOUS.intValue() &&RequestContext.isAnonymousUser()) {
			return this.getRedirectView("/login.html?fromCheckout=1");
		}
		Map<String, Object> data = new HashMap<String, Object>();
		ProductReview review = productReviewManager.getById(RequestUtil.getInteger(request, "productReviewId"));
		ProductReview reply = new ProductReview();
		reply.setParent(review);
		reply.setCustomer((AppUser) RequestContext.getCurrentUser());
		reply.setRemoteIp(request.getRemoteAddr());
		reply.setAddress(IPSeeker.getInstance().getAddress(reply.getRemoteIp()));
		reply.setProduct(review.getProduct());
		reply.setMessage(RequestUtil.getParameterNullSafe(request, "message"));
		reply.setCustomerName(request.getParameter("customerName"));
		reply.setIsRead(ProductReview.STATUS_UNREAD);
		reply.setSortOrder(ProductReview.STATUS_UNTOP);
		reply.setStatus(ProductReview.STATUS_SHOW);
		reply.setScore(new BigDecimal("0"));
		productReviewManager.addReply(reply);
		
		//清空该商品页面缓存
		EventUtil.getInstance().fire(new StoreFrontCache4ProductClearEvent(this,review.getProductId()));
		
		return this.getModelAndAjaxJsonView(data);
		
	}
	
	/**
	 * 发表评论
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView addReview(HttpServletRequest request,HttpServletResponse response){
		//如果评论不允许非匿名登录，且目前没登录，跳转到登录页
		if (ConfigUtil.getInstance().getCustomerReviewRight().intValue() != ProductReview.REVIEW_RIGHT_ANONYMOUS.intValue() && RequestContext.isAnonymousUser()) {
			return this.getRedirectView("/login.html?fromCheckout=1");
		}
		Product product = productManager.getById(RequestUtil.getInteger(request, "productId"));
		ProductReview review = new ProductReview();
		review.setProduct(product);
		review.setSubject(RequestUtil.getParameterNullSafe(request, "subject"));
		review.setMessage(RequestUtil.getParameterNullSafe(request, "message"));
		review.setCustomerName(request.getParameter("customerName"));
		review.setScore(new BigDecimal(RequestUtil.getParameterNullSafe(request, "score")));
		review.setCreateTime(new Date());
		review.setCustomer((AppUser) RequestContext.getCurrentUser());
		review.setRemoteIp(request.getRemoteAddr());
		review.setAddress(IPSeeker.getInstance().getAddress(review.getRemoteIp()));
		review.setIsRead(ProductReview.STATUS_UNREAD);
		review.setSortOrder(ProductReview.STATUS_UNTOP);
		review.setStatus(ProductReview.STATUS_SHOW);
		review.setUsefulCount(Integer.valueOf(0));
		review.setUnusefulCount(Integer.valueOf(0));
		review.setReplyCount(Integer.valueOf(0));
		review.setOnShowReplyCount(Integer.valueOf(0));
		productReviewManager.addReview(review);
		
		//清空该商品页面缓存
		EventUtil.getInstance().fire(new StoreFrontCache4ProductClearEvent(this,review.getProductId()));
		
		return this.getRedirectView(productManager.getReviewUriByProduct(product));
		
	}
	
	
}
